#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>

int flags = 1;

void handlr_signal(int sig){
    flags = 0;
    kill(getppid(),SIGTERM);
}

int main(int argc, char const *argv[])
{
    
    int fd[2];

    if(pipe(fd) < 0){
        perror("pipe error");
        exit(-1);
    }

    printf("Afd[0]:%d,fd[1]:%d\n", fd[0], fd[1]);
    pid_t pid = fork();
    if(pid < 0) {
        perror("fork error");
        exit(-1);
    } else if (pid > 0){
        signal(SIGINT,SIG_IGN);
        char buf[20]={0};
        printf("Bfd[0]:%d,fd[1]:%d\n", fd[0], fd[1]);
        while(1){
            write(fd[1], "hello world", sizeof("hello world"));
            sleep(1);
        }
        //wait(NULL);  // 等待子进程结束
    } else {
        signal(SIGINT, handlr_signal);
        printf("Cfd[0]:%d,fd[1]:%d\n", fd[0], fd[1]);
        char buf[20] = {0};
        // close(fd[1]);  // 子进程关闭写端
        while(flags){
            read(fd[0], buf, sizeof(buf));
            printf("buf=%s\n", buf);
        }
    }
    return 0;
}
